package com.atguigu.gulimail.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * [说明/描述]
 *
 * @author 陈新乐
 * @version 1.0
 * @date 2024/8/1
 */
@RestControllerAdvice
@Slf4j
public class GulimailExceptionControllerAdvice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleException(MethodArgumentNotValidException bindException) {
        log.error("数据校验问题{}，异常类型{}",bindException.getMessage(),bindException.getClass());
        HashMap<String, String> errorMessage = new HashMap<>();
        bindException.getBindingResult().getFieldErrors().forEach(fieldError -> {
            errorMessage.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMsg()).put("data",errorMessage);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Exception e) {
        return R.error(500,e.getMessage());
    }
}
